#!/bin/bash

VERSION=1.4.3
FILE=zstd-$VERSION.tar.gz
DIR=zstd-$VERSION
URL=https://github.com/facebook/zstd/archive/v$VERSION.tar.gz

rm /tmp/zstd.XXXX.log >/dev/null 2>&1 || true

logfile=$(mktemp /tmp/zstd.XXXX.log)
exec 3>"$logfile"

function silent_run
{
    eval "$@ >&3 2>&1"
}

function silent_trun
{
    eval "$@ >&3 2>&1 || true"
}

function do_then_sudo
{
    eval "$@"
    if [ $? != 0 ]; then
        eval "sudo $@"
    fi
}

function failed
{
    echo "FAILED."
    echo "[_/_] LOG OUTPUT:"
    cat $logfile
    exit 1
}

silent_trun rm $FILE
silent_trun rm -rf $DIR

echo -n "[1/3] Downloading... "
silent_run curl -o $FILE -L $URL
[ $? == 0 ] && echo "done." || failed

tar xzf $FILE && cd $DIR

echo -n "[2/3] Compiling... "
silent_run make
[ $? == 0 ] && echo "done." || failed

echo -n "[3/3] Installing... "
silent_run do_then_sudo make install
[ $? == 0 ] && echo "done." || failed

cd ..
silent_trun rm $FILE
silent_trun rm -rf $DIR

if type "ldconfig" >/dev/null 2>&1; then
    silent_run do_then_sudo ldconfig
fi

rm "$logfile" || true
